package zzu.xjc.http;


import java.io.IOException;
import java.nio.channels.SocketChannel;

/**
 * @Author Xiejc
 * @Date 2021/8/6 11:00
 * @Description Encapsulates a ThreadWorker array
 *              封装了一个ThreadWorker数组
 * @Since version-1.0
 */
public class Workers {
    private ThreadWorker[] threadWorkers;
    private HttpServiceExecutor executor;
    private BufferPool bufferPool;
    private int threads;
    private int currIndex = 0;

    /* 只有Acceptor线程会调用这个方法，所以不需要把方法currentWorker()和类成员变量currIndex原子化
     * Only Acceptor thread will call this method, so there is no need to
     *  make method currentWorker() and class member variable currIndex atomic
     * */
    private ThreadWorker currentWorker(){
        /* make every threadWorker load more balance */
        if ( ++currIndex >= threads){
            currIndex = 0;
        }
        return threadWorkers[currIndex];
    }

    void register(SocketChannel channel){
        currentWorker().register(channel);
    }

    void init(int threads) throws IOException {
        this.threads = threads;
        threadWorkers = new ThreadWorker[threads];
        for (int i = 0; i < threads; i++) {
            threadWorkers[i] = new ThreadWorker(i);
            threadWorkers[i].inject(executor,bufferPool);
        }
    }

    void inject(HttpServiceExecutor executor,BufferPool bufferPool){
        this.executor = executor;
        this.bufferPool = bufferPool;
    }

    void start(){
        for (int i = 0; i < threadWorkers.length; i++) {
            threadWorkers[i].start();
        }
    }
}

